
var App = klass(function() {

}).statics({
	_eventContext: null,
	_loadingPanel: null,
	_user: null,

	getUser: function() {
		return App._user;
	},

	setUser: function(user) {
		App._user = user;
	},

	crudGridInstance: function() {
		return $(".crud-grid").dxDataGrid("instance");
	},

	getFormInstance: function() {
		return $("#form").dxForm("instance");
	},

	getEventContext: function() {
		return App._eventContext;
	},

	setEventContext: function(v) {
		App._eventContext = v;
	},

	showLoading: function(message) {
		message = message || '正在加载...';

		App._loadingPanel = $("#loadpanel").dxLoadPanel({
        	shadingColor: "rgba(0,0,0,0.4)",
        	position: { of: "body" },
        	visible: true,
        	showIndicator: true,
        	showPane: true,
        	shading: true,
        	closeOnOutsideClick: false,
        	message: message
    	}).dxLoadPanel("instance");
	},

	hideLoading: function() {
		if (App._loadingPanel !== null) {
			App._loadingPanel.hide();
			App._loadingPanel = null;
		}
	}
});

jQuery.extend({
	crudStoreResp: null,

	crudStore: function(url, options) {

		var SERVICE_URL = url;
		options = $.extend({
			onDataArrived: function(data) {
				return data;
			}
		}, options);

		return new DevExpress.data.CustomStore($.extend({}, options, {

			load: function(loadOptions) {

				var u = new Url(SERVICE_URL);

				u.query._param = JSON.stringify(loadOptions);

				return $.getJSON(u).then(function(resp) {
					console.log("data done");
					return options.onDataArrived(resp);
				});
			},

			byKey: function(key) {
				var u = new Url(SERVICE_URL);
				u.path += "/" + encodeURIComponent(key);

				return $.getJSON(u).then(function (resp) {
					return resp.data;
				});
			},

			insert: function(values) {
				console.log(values);
				return $.post(SERVICE_URL, values).always(function(resp) {
					$.crudStoreResp = resp.responseJSON;
					return resp;
				});
			},

			update: function(key, values) {
				var u = new Url(SERVICE_URL);
				u.path += "/" + encodeURIComponent(key);

				return $.ajax({
					url: u,
					method: "PUT",
					data: values,
				}).always(function(resp) {
					$.crudStoreResp = resp.responseJSON;
					return resp;
				});
			},

			remove: function(key) {
				var u = new Url(SERVICE_URL);
				u.path += "/" + encodeURIComponent(key);

				return $.ajax({
					url: u,
					method: "DELETE"
				});
			}

		}));
	},

	crud: function(options) {
		if(typeof(options) === 'object') {
			var app = options.app,
				route = options.route,
				store = jQuery.crudStore(options.url || API(route), options.store);


			options.search = $.extend({
				mobile: 'mobile',
				name: 'uname',
				dateA: 'dateA'
			}, options.search);

			// list

			app.get('#/' + route, function() {
				var eventContext = this,
					capable = $.extend({
						create: true
					}, options.capable);
				$('#content').html(Mustache.render($("#crud-list").html(), $.extend({}, options, {
					capable: capable
				}))).dxInit();

				var gridType = options.gridType || "dxDataGrid";

				if(options.buttons) {
					$.each(options.buttons, function(i, button) {
						button.instance = $("<div>").dxButton($.extend({
							type: 'normal',
							onClick: function(e) {
								var selections = [];

								if(options.onGetSelectedRowsData) {
									selections = options.onGetSelectedRowsData.call(eventContext, $("#content .crud-grid"));
								} else if(!options.onRenderGrid) {
									selections = $("#content .crud-grid")[gridType]('getSelectedRowsData');
								}

								button.onRoute && button.onRoute.call(eventContext, e.component, selections);
							}
						}, button)).appendTo(
							$("#content .crud-buttons")).dxButton('instance');
					});
				}

				var defaultToolbarItems = [];
				if (options.capable.create) {
					defaultToolbarItems.push('create');
				}

				var toolbarOptions = options.toolbar ? options.toolbar : {
					items: defaultToolbarItems
				};

				$.each(toolbarOptions.items, function(i, item) {
					if (item === 'create') {
						toolbarOptions.items[i] = {
							location: 'before',
							widget: 'dxButton',
							options: {
								text: '新建',
								onClick: function() {
									eventContext.redirect('#/' + route + '/edit');
								}
							}
						};
					}
				});

				console.log(toolbarOptions);
				$("#content .toolbar").dxToolbar(toolbarOptions);

				var ds = new DevExpress.data.DataSource({
					store: store
				});

				if(eventContext.params) {
					$.each(eventContext.params, function(k, v) {
						if(typeof(v) !== 'function' && typeof(v) !== 'object') {
							ds.filter(k, '=', v);
						}
					});
				}


				var param = {
					dataSource: ds,
					allowColumnResizing: true,
					selection: {
						mode: "multiple",
						showCheckBoxesMode: 'always',
						selectAllMode: 'page'
					},
					remoteOperations: true,
					paging: {
						pageSize: 10,
						pageIndex: 0
					},
					onSelectionChanged: function(e) {
						$.each(options.buttons, function(i, button) {
							button.onSelectionChanged &&
								button.onSelectionChanged.call(eventContext, button.instance, e.selectedRowsData, e.component);
						});
					}
				};

				if(options.columns) {
					for(var i = 0; i < options.columns.length; i++) {
						if(options.columns[i].buttons) {

							options.columns[i].cellTemplate = (function(buttons) {
								return function(container, ei) {

									$.each(buttons, function(i, button) {
										var title = button.title,
											url = '#';

										if(button.url) {
											url = Mustache.render(button.url, ei.data);
										}

										var el = $(Mustache.render('<a style="margin: 0 10px;" href="{{url}}">{{title}}</a>', {
											title: title,
											url: url
										}));

										if(button.onClick) {
											el.click(function() {

												button.onClick(ei.data, ei.component);
												return false;
											});
										}

										el.appendTo(container);



								if(button.del){

						$("<span style='margin:0 5px;vertical-align:1px'>|</span>").appendTo(container)

										 $("<a>").text("删除").click(function(){

								     DevExpress.ui.dialog.confirm("确定删除吗?", "请确认").done(function(sele){

							                if(sele){
                                           var  getId= ei.data.id
                               
 								           $.ajax({type:"delete",
 						                   url:$.config('apiUrl')+"restful/"+getId+"?_model="+button.del
								                 }).then(function(a){

								                if(a.status="success"){

								                    DevExpress.ui.notify({
								                      message: function() {

								                       gridComponent = $("#content .crud-grid").dxDataGrid('instance');

								                     gridComponent.option('dataSource').load();

								                       return "成功删除";
								                                     }
								                                   },"success", 1000)

								                               }else{

								                    DevExpress.ui.notify({

								                      message: function() {

								                       return "操作失败";
								                                     }
								                                   },"warning", 1000)
								                         }
								                      })
								                    }
								                })
								        }).appendTo(container)

										}

									});
								};
							})(options.columns[i].buttons);
						}
					}
					param['columns'] = options.columns;
				}

				if(options.onRenderGrid) {
					options.onRenderGrid.call(eventContext, $("#content .crud-grid"), $.extend({}, param, options.grid));
				} else {
					$("#content .crud-grid")[gridType]($.extend({}, param, options.grid));
				};

				// var gridInst = $("#content .crud-grid")[gridType]("instance");

				if(!options.search['mobile']) $("#content [data-search=mobile]").closest(".input-group").hide();
				if(!options.search['name']) $("#content [data-search=name]").closest(".input-group").hide();
				if(!options.search['lookup']) $("#content [data-search=lookup]").closest(".lookup").hide();
				if(!options.search['mobile'] && !options.search['name']) {
					$("#content .grid-search").hide();
				}

				var now = new Date()
				$("#date").dxDateBox({
					type: "date",
					value: now,
					displayFormat: 'yyyy-MM-dd',
					dateSerializationFormat: "yyyy-MM-dd",
					editorOptions: {
						displayFormat: 'yyyy-MM-dd',
						dateSerializationFormat: 'yyyy-MM-dd'
					}
				})

				$("#content .grid-search").click(function() {
					var name = $("#content [data-search=name]").val(),
						mobile = $("#content [data-search=mobile]").val(),
						dateA = $("#content #date").dxDateBox('option', 'value');

					if(name) {
						ds.searchExpr(options.search['name']);
						$("#content [data-search=mobile]").val('');
					} else if(mobile) {
						ds.searchExpr(options.search['mobile']);
						$("#content [data-search=name]").val('');
					} else if(dateA) {
						ds.searchExpr(options.search['dateA']);
						$("#content #date").dxDateBox('option', 'value');
					}

					ds.searchOperation("contains");
					ds.searchValue(name || mobile || dateA);
					ds.reload();
				});

				// $("#modify_pwd", $(this)).dxDataGrid(param);
			});

			function initCrudForm($c, context) {
				var id = context.params.id,
					formOptions = {
						readOnly: false,
						showColonAfterLabel: true,
						showValidationSummary: false,
						colCount: 1,
						validationGroup: "crud",
						items: [],
						onFieldDataChanged: function(e) {
							// console.log("onFieldDataChanged");
							// console.log(e);
						}
					};

					

				if(id) {
					formOptions.onContentReady = function(e) {
						store.byKey(id).then(function(resp) {

							if (options.form.beforeDataUpdate) {
								options.form.beforeDataUpdate(form, {data: resp});
							}
							e.component.option('formData', resp);

							if(options.form.afterDataUpdate) {
								options.form.afterDataUpdate(form, {data: resp});
							}
						});
					}
				}

				var items = [];
				if (options.form && options.form.items) {
					var scene = (id ? 'edit' : 'create');
					$.each(options.form.items, function(i, item) {
						if (item.scene && $.inArray(scene, item.scene) < 0) {

						} else {
							items.push(item);
						}
					});
				}

				var form = $("#form", $c).dxForm($.extend(formOptions, options.form, {items: items})).dxForm('instance');

				$("#form-container #save", $c).click(function () {
					var result = form.validate();

					if (! result.isValid) {
						var $el = result.validators[0].element();

						var offset = $el.offset();

						$('html, body').animate({
						    scrollTop: offset.top - $("header.app-header").height() - 20
						});

					} else {
						$("#form-container", $c).submit();
					}

					return false;
				});

				$("#form-container", $c).on("submit", function(e) {
					var bs = true;
					if(options.form.beforeSubmit) {
						bs = options.form.beforeSubmit(form, id);
					}

					$.when(bs).then(function(result) {
						if(result) {
							if(id) {
								store.update(id, form.option('formData')).then(function(values, resp) {
									DevExpress.ui.notify({
										message: "已更新",
									}, "success", 1000);
									if (options.form.onSaved) {
                                        options.form.onSaved.call(context, values, resp);
                                    } else {
                                        context.redirect('#/' + route);
                                    }
								}).fail(function() {
									DevExpress.ui.notify({
										message: $.crudStoreResp.message
									}, "warning", 2000);
								});
							} else {
								store.insert(form.option('formData')).then(function(values, resp) {
									if(resp.status == "error") {
										DevExpress.ui.dialog.alert(resp.msg, '提示');
										return false;
									} else {
										DevExpress.ui.notify({
											message: "已完成",
										}, "success", 1000);
										context.redirect('#/' + route);
										//		        						context.redirect('#/' + route + '/edit/' + resp.model.id);
									}
								}).fail(function(resp) {
									DevExpress.ui.notify({
										message: resp,
									}, "warning", 2000);
								});
							}
						}
					})

					return false;
				});

				$("#form-container .delete", $c).click(function() {
					DevExpress.ui.dialog.confirm("确认删除吗?", "请确认").done(function(dialogResult) {
						if(dialogResult) {

							store.remove(id).then(function(resp) {

								DevExpress.ui.notify({
									message: "已删除",
								}, "success", 1000);
								context.redirect("#/" + route);
							});
						}
					});

					return false;
				});

				$("#form-container #cancel").click(function() {
					context.redirect("#/" + route);
					return false;
				});

				var saveNext = false;
				$("#form-container #save").click(function() {
					saveNext = false;
					return false;
				});
				$("#form-container #save-next").click(function() {
					saveNext = true;
					return false;
				});
			}

			// create or edit
			//			console.log("add crud " + route + "/edit");

			app.get('#/' + route + "/edit", function() {
				var eventContext = this,
					capable = $.extend({
						saveNext: true
					}, options.capable);
				$('#content').html(Mustache.render($("#crud-form").html(), $.extend({}, options, {
					capable: capable,
					role: '新建'
				}))).dxInit();

				initCrudForm($("#content"), this);
			});

			//			console.log("add crud " + route + "/edit/:id");

			app.get('#/' + route + "/edit/:id", function() {
				var eventContext = this,
					capable = $.extend({
						delete: true
					}, options.capable);
				$('#content').html(Mustache.render($("#crud-form").html(), $.extend({}, options, {
					capable: capable,
					role: '编辑'
				}))).dxInit();

				initCrudForm($("#content"), this);
			});
		}
	},

	dxCall: function() {
		var comp = $(this).data('dxComponents');
		if(comp && comp.length) {
			var inst = $(this)[comp[0]]("instance");

			return inst[arguments[0]].apply(inst, arguments.slice(1));
		} else {
			return undefined;
		}
	}
});

var routes = [
	'dashboard',
	'member-relations/show/:id',
	'member-check/:id',
	'subject-investor/:action',
	'subject-investor/:action/:id',
	'subject-agent/:action',
	'subject-agent/:action/:id',
	'page_vipclass',
	'table_vipcert',
	'page_vipcontacts',
	'page_vipbonus',
	'tz_management',
	'xz_contract',
	'tz_edit',
	'qy_management',
	'qy_form',
	'qy_edit',
	'order_list',
	'shj_management',
	'to_examine',
	'play_money',
	'money_details',
	'already_money',
	'examine_refuse',
	'user_management',
	'qy_managements',
	'now_list',
	'pt_bonus',
	'modify_pwd',
	'newproduct/:id',
	'newproduct',
	'rightsConsumes',
	'rightsChanges',
	'vip_information/:id',
	'vip_authority/:id',
	'project-details/:id',
	'integral-details/:id',
	'project-edit/:id',
	'score-details/:id'
];



var crudPages = [];
crudPages.push({
	route: 'product',
	url: API('restful?_model=product'),
	title: '产品',
	placeholder: '红酒名称',
	capable: {
		create: true
	},
	toolbar: {
		items: [{
			location: 'before',
			widget: 'dxButton',
			options: {
				text: '新建',
				onClick: function() {
					App.getEventContext().redirect('#/newproduct');
				}
			}
		}]
	},
	search: {
		mobile: 'nickname',
	},
	columns: [{
			dataField: 'id',
			caption: 'id'
		}, {
			dataField: 'chname',
			caption: '葡萄酒名称'
		}, {
			dataField: 'weight',
			caption: '权重',
			cellTemplate:function(con,da){
				$(con).dxWeight("product",da)			}
		}, {
			dataField: 'online',
			caption: '上下线',
			cellTemplate: function(con, opt) {
				$(con).dxUpdown('product',opt)

			}
		}, {minWidth:100,
			caption: '操作',
			buttons: [{
				title: '编辑',
				url: '#/newproduct/{{id}}',
				del:'wine-product'
			}]

		},
		{
			caption: '预览',
			buttons: [{
				title: "预览"
			}]
		}, {
			dataField: 'pv',
			caption: 'pv'
		}, {
			dataField: 'uv',
			caption: 'uv'
		}, {
			dataField: 'want_drink',
			caption: '想喝'
		}, {
			dataField: 'has_drink',
			caption: '喝过'
		}, {
			dataField: 'order_count',
			minWidth: 100,
			caption: '订单量'
		}
	]

});
crudPages.push({
	route: 'product-drink',
	url: API('restful?_model=wine-product-drink'),
	title: 'Drink介绍',
	placeholder: '昵称',
	capable: {
		create: false
	},
	search: {
		mobile: 'nickname',
	},
	columns: [{
		dataField: 'avatar',
		caption: '会员头像',
		allowFiltering: false,
		allowSorting: false,
		cssClass: 'avatarImg',
		cellTemplate: function(container, options) {
			$("<div>").append($("<img>", {
				"src": options.value
			})).appendTo(container);
		}
	}, {
		dataField: 'nickname',
		caption: '会员昵称'
	}, {
		dataField: 'username',
		caption: '会员姓名'
	}, {
		dataField: 'point',
		caption: '会员积分'
	}, {
		minWidth: 120,
		caption: '操作',
		buttons: [{
			title: '查看',
			url: '#/integral-details/{{id}}'
		}]
	}]
});

crudPages.push({
	route: 'product-judge',
	url: API('restful?_model=wine-product-judge'),
	title: '专业品鉴',
	placeholder: '昵称',
	capable: {
		create: false
	},
	search: {
		mobile: 'nickname',
	},
	columns: [{
		dataField: 'avatar',
		caption: '会员头像',
		allowFiltering: false,
		allowSorting: false,
		cssClass: 'avatarImg',
		cellTemplate: function(container, options) {
			$("<div>").append($("<img>", {
				"src": options.value
			})).appendTo(container);
		}
	}, {
		dataField: 'nickname',
		caption: '会员昵称'
	}, {
		dataField: 'mobile',
		caption: '手机号'
	}, {
		dataField: 'email',
		caption: '邮箱'
	}, {
		dataField: 'publish_project_count',
		caption: '项目发布数量'
	}, {
		dataField: 'execute_project_count',
		caption: '项目执行数量'
	}, {
		dataField: 'rank',
		caption: '评分'
	}, {
		caption: '操作',
		buttons: [{
			title: '查看',
			url: '#/score-details/{{id}}'
		}]
	}]
});

crudPages.push({
	route: 'product-technique',
	url: API('restful?_model=win-product-technique'),
	title: '技术信息',
	placeholder: '昵称',
	capable: {
		delete: false,
		create: false
	},
	search: {
		mobile: 'nickname',
	},
	columns: [{
		dataField: 'avatar',
		caption: '会员头像',
		allowFiltering: false,
		allowSorting: false,
		cssClass: 'avatarImg',
		cellTemplate: function(container, options) {
			$("<div>").append($("<img>", {
				"src": options.value
			})).appendTo(container);
		}
	}, {
		dataField: 'nickname',
		caption: '会员昵称'
	}, {
		dataField: 'email',
		caption: '邮件地址'
	}, {
		dataField: 'mobile',
		caption: '手机号'
	}, {
		dataField: 'username',
		caption: '会员姓名'
	}, {
		dataField: 'id_card',
		caption: '身份证'
	}, {
		dataField: 'is_publish',
		caption: '需求录入创客'
	}, {
		dataField: 'is_execute',
		caption: '任务执行创客'
	}, {
		dataField: 'is_manager',
		caption: '项目经理'
	}, {
		dataField: 'created_at',
		caption: '加入时间'
	}, {
		dataField: 'linkman_count',
		caption: '联系人',
		tellTemplate: function(container, options) {
			$("<div>").text(options.data.linkman_count).appendTo(container)
		}
	}, {
		minWidth: 120,
		caption: '操作',
		buttons: [{
			title: '配置权限',
			url: '#/vip_authority/{{id}}'
		}]
	}],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		items: [{
			itemType: "group",
			items: [{
				dataField: "mobile",
				label: {
					text: '会员手机'
				},
				validationRules: [{
					type: "required",
					message: "请输入会员手机号"
				}, {
					type: "pattern",
					pattern: /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/,
					message: "手机号格式错误"
				}]
			}, {
				dataField: "username",
				label: {
					text: '会员姓名'
				},
			}, {
				dataField: "identity_card",
				label: {
					text: '会员证件号'
				},
			}, {
				dataField: "remark",
				editorType: "dxTextArea",
				label: {
					text: '备注'
				},
				editorOptions: {
					height: 140
				}
			}]
		}]
	}
});

crudPages.push({
	route: 'product-score',
	url: API('restful?_model=wine-product-score'),
	title: '专业评分',
	capable: {
		create: false
	},
	search: {
		mobile: false,
		lookup: true,
		dateA: 'dividend_date'
	},
	columns: [{
		dataField: 'dividend_date',
		caption: '分红日期',
		sortOrder: 'desc'
	}, {
		dataField: 'user_count',
		caption: '分红用户数'
	}, {
		dataField: 'partake_total',
		caption: '参与分红总金额（万元）',
		format: function(v) {
			return parseFloat(v).toFixed(2);
		}
	}, {
		dataField: 'plan_price',
		caption: '分红金额/万元',
		format: function(v) {
			return parseFloat(v).toFixed(2);
		}
	}, {
		dataField: 'dividend_total',
		caption: '分红总金额',
		format: function(v) {
			return parseFloat(v).toFixed(2);
		}
	}]
});

crudPages.push({
	route: 'subjectType',
	title: '标的物类型',
	capable: {
		create: false
	},
	buttons: [],
	columns: [{
		dataField: 'code',
		caption: '标的物类型代码'
	}, {
		dataField: 'name',
		caption: '标的物类型'
	}, {
		dataField: 'project',
		caption: '所属项目',
	}, {
		dataField: 'price',
		caption: '单价',
	}, {
		dataField: 'created_at',
		caption: '创建时间'
	}]
});

crudPages.push({
	route: 'subjects',
	title: '售货机',
	capable: {
		create: false
	},
	buttons: [{
		text: '数据同步',
		onClick: function() {
			alert('not implemented');
		}
	}],
	columns: [{
		dataField: 'code',
		caption: '售货机编号'
	}, {
		dataField: 'name',
		caption: '售货机名称'
	}, {
		dataField: 'subject_area',
		caption: '所属区域',
		cellTemplate: function(el, ei) {
			el.text(ei.data.subject_area.QXMC);
		}
	}, {
		dataField: 'updated_at',
		caption: '更新时间'
	}]
});

crudPages.push({
	url: API('restful?_model=wine-chateau'),
	route: 'chateau',
	title: '酒庄',
	capable: {
		create: true
	},
	columns: [{
			dataField: 'id',
			caption: 'id'
		}, {
			dataField: 'chname',
			caption: '酒庄名称'
		},
		{
			dataField: 'weight',
			caption: '权重',
			cellTemplate:function(con,da){
				con.dxWeight('chateau',da)
			}
		},
		{
			dataField:'online',
			caption:'上下线',
			cellTemplate:function(con,da){
				con.dxUpdown('chateau',da)
			}
		},
		{
			caption: "操作",
			buttons:[{
				title:'编辑',
				url:'#/chateau/edit/{{id}}',
				del:'wine-chateau'
			}]
		}
	],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		afterDataUpdate: function(formInstance, data) {
			//console.log(formInstance.geiEditor("#editor"));

		},
		beforeSubmit: function(form, id) {
			var formData = form.option('formData');
			
			formData.state='publish';

			form.option('formData', formData);
			
			function pic(data){
				var chateau=[];
				if(data && data.length > 0){
				$.each(data,function(er,da){
					chateau.push( da.id );
				})	
				;
			};
			return chateau.join()
			};
		formData.master_pic_ids = pic(formData.chateau_master_pic);
		formData.pic_ids = pic(formData.chateau_pic);
		formData.grapery_pic_ids = pic(formData.chateau_grapery_pic);
			console.log(formData)
			return true;
		},
		
		items: [{
			itemType: "group",

			items: [{
					dataField:'chateauCode',
					label:{text:'酒庄编码'},
					validationRules: [{
			            type: "required",
			            message: "请输入酒庄编码"
	    			}, {
	    				type: 'pattern',
	    				pattern: /^[A-Z0-9]{2,5}$/,
	    				message: '酒庄编码必须是5位以内的大写字母或数字组合'
	    			}],
					editorType:"dxTextBox",
					helpText: '5位以内的大写字母或数字组合（至少2位）'
				} ,{
					dataField: "chname",
					validationRules: [{
			            type: "required",
			            message: "请输入中文名称"
	    			   }],
					label: {
						text: '中文名称'
					}
				}, {
					dataField: "name",
					validationRules: [{
			            type: "required",
			            message: "请输入中文名称"
	    			   }],
					label: {
						text: '英文名称'
					}
				},{
					dataField: "chateau_pic",
					validationRules: [{
			            type: "required",
			            message: "封面图片"
	    			   }],
					editorType: "ImageUploader",
					editorOptions: {
						imageWidth: 750,
						imageHeight: 838
					},
					label: {
						text: '封面图片'
					}

				},
				 {
					dataField:'produce_id',
					validationRules: [{
			            type: "required",
			            message: "请输入生产商"
	    			}],
					label: { text:'生产商' },
					editorType: 'dxSelectBox',
					editorOptions: {
						dataSource: $.crudStore(API('restful?_model=sys-produce')),
						showClearButton: true,
						placeholder: "生产商",
						searchEnabled: true,
						valueExpr: 'id',
						noDataText: '没有请求到生产商数据',
						itemTemplate: function(data, index, $el) {
						  if (data) {
						    $("<span>" + data.chname + " (" + data.name + ")</span>").appendTo($el);
						  }
						},
						displayExpr: function(data) {
						  return data ? data.chname + " (" + data.name + ")" : "";
						}
					},
								
				}, 
				{
					dataField: "address",
					validationRules: [{
			            type: "required",
			            message: "请输入地址"
	    			   }],
					label: {
						text: '地址'
					}
				}, {
					dataField: "levelType",
					label: {
						text: '酒庄评级系统'
					}

				}, {
					dataField: "website",
					label: {
						text: '官网链接'
					}
				},
				{
					dataField:'intro',
					validationRules: [{
			            type: "required",
			            message: "请输入酒庄介绍"
	    			   }],
					editorType:'dxEditor',
					label:{
						text:'酒庄介绍'
					}
				},
				{
					dataField: "feature",
					validationRules: [{
			            type: "required",
			            message: "请输入酒庄特点"
	    			   }],
					label: {
						text: "酒庄特点"
					},
					editorType:'dxEditor'
				},
				{
					dataField:'chateau_master_pic',
					label:{
						text:"庄主照片"
					},
					editorType:'ImageUploader',
					editorOptions: {
						imageWidth: 750,
						imageHeight: 422
					}
				},
				{
					dataField:'owner',
					label:{
						text:'庄主姓名'
					}
				},
				{
					dataField:'owner_intro',
					label:{
						text:'庄主介绍'
					},
					editorType:"dxTextArea",
					editorOptions:{
						height:120
					}
				},
				{
					dataField:"area",
					label:{
						text:'葡萄园面积'
					}
				},
				{
					dataField:'chateau_grapery_pic',
					label:{
						text:"葡萄园图片"
					},
					editorType:"ImageUploader",
					editorOptions: {
						imageWidth: 750,
						imageHeight: 422
					}
				},
				{
					dataField:'chateau_grapery',
					label: { text: ' ', showColon: false },
					editorType: 'GrapeList'
					//占位
				},
				{
					dataField:"age",
					label:{
						text:'平均树龄'
					}
				},
				{
					dataField:"soil",
					label:{
						text:"土壤类型"
					},
					editorType:"dxTextArea",
					editorOptions: {
						autoResizeEnabled: true
					}
				},
				{
					dataField:'harvest',
					label:{
						text:"采收方式"
					},
					editorType:'dxTextArea',
					editorOptions:{
						autoResizeEnabled: true
					}
				}
			]
		}]
	}

});

crudPages.push({
	route: 'restful',
	url: API('restful?_model=cms-article'),
	title: '文章',
	placeholder: '文章名称',
	capable: {
		create: true
	},
	search: {
		mobile: 'title'
	},
	toolbar: {
		items: ['create', {
			location: 'after',
			widget: 'dxSelectBox',
			options: {
				width: 150,
				dataSource: $.crudStore(API('restful?_model=cms-article-column')),
				valueExpr: 'id',
				displayExpr: 'name',
				showClearButton: true,
				placeholder: '按文章分类',
				onValueChanged: function(e) {
					var ds = App.crudGridInstance().option('dataSource');

					if (e.value) ds.filter('column_id', '=', e.value);
					else ds.filter(null);

					ds.reload();
				}
			}
		}]
	},
	columns: [{
		dataField: 'id',
		caption: 'id'
	}, {
		dataField: 'title',
		caption: '文章名称'
	}, {
		dataField: 'column_name',
		caption: '栏目'
	}, {
		dataField: 'weight',
		caption: '权重',
		cellTemplate:function(con,dat){
			$(con).dxWeight('article',dat)
		}
	}, {
		dataField: 'online',
		caption: '上下线',
		cellTemplate:function(con,dat){

			$(con).dxUpdown('article',dat)
		}
	}, {
		dataField: "content",
		caption: '操作',
		buttons:[{
			title:'编辑',
			url:'#/restful/edit/{{id}}',
			del:'cms-article'
		}]
	},{
		dataField:'pv',
		caption:'PV'
	},{
		dataField:'uv',
		caption:'UV'
	},{
		dataField:'collection_quantity',
		caption:'收藏量'
	}],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		beforeDataUpdate: function(formInstance, data) {
			if (data.data.column_id) {
				data.data.column_id = parseInt(data.data.column_id);
			}

			data.data.column = undefined;
		},
		afterDataUpdate: function(formInstance, data) {
			//console.log(formInstance.geiEditor("#editor"));

		},
		beforeSubmit: function(form, id) {
			var formData = form.option('formData');

			formData.video_type = 'url';

			var cover = [];
			$.each(formData.covers, function(i, cov) {
				cover.push(cov.id)
			});
			if(cover.length == 0) {
				formData.cover_ids = 0;
			} else {
				formData.cover_ids = cover.join()
			};

			formData.state='publish';

			form.option('formData', formData);
			return true;
		},
		items: [{
			label: {text:'文章'},
			editorType:'dxRadioGroup',
			dataField: 'type',
			editorOptions:{
				layout: "horizontal",
				items:[
				{
					text:'文章',
					value:'article'
				}, {
					text:'视频',
					value:'video'
				}],
    			valueExpr: 'value',
    			onValueChanged: function(e) {
    				var formInstance = e.element.closest(".dx-form").dxForm("instance");

    				if (e.value === 'article') {
	    				formInstance.getEditor('video_path').element().closest(".dx-field-item").addClass("hidden");
	    				formInstance.getEditor('content').element().closest(".dx-field-item").removeClass("hidden");
    				} else {
	    				formInstance.getEditor('video_path').element().closest(".dx-field-item").removeClass("hidden");
	    				formInstance.getEditor('content').element().closest(".dx-field-item").addClass("hidden");
    				}
    			}
			}
		}, {
			label: { text: '列表方式' },
			editorType: 'dxRadioGroup',
			dataField: 'feature',
			validationRules: [{ type: "required" }],
			editorOptions:{
				layout: "horizontal",
				items:[{
					text: '大图',
					value: 1
				}, {
					text: '小图',
					value: 0
				}],
    			valueExpr: 'value',
			}
		}, {
			dataField: "title",
			validationRules: [{ type: "required" }],
			label: {
				text: '文章名称'
			}
		}, {
			dataField: "author",
			label: {
				text: '作者'
			}
		}, {
			dataField: "column_id",
			validationRules: [{ type: "required" }],
			label: {
				text: '栏目'
			},
			editorType: 'dxSelectBox',
			editorOptions: {
				dataSource: $.crudStore(API('restful?_model=cms-article-column')),
				showClearButton: true,
				placeholder: "分类",
				searchEnabled: true,
				valueExpr: 'id',
				displayExpr: 'name',
				noDataText: '没有请求到分类数据',
				deferRendering: false,
				itemTemplate: function(data) {
					return data.name
				}
			}

		}, {
			dataField: "abstract",
			label: {
				text: '摘要'
			}
		},
		{
			dataField: "covers",
			name: "name",
			editorType: "ImageUploader",
			label: {
				text: '封面图片'
			},
			editorOptions: {
				imageWidth: 750,
				imageHeight: 422
			}

		},
		{	dataField:'content',
			label:{text:'文章正文'},
			editorType:'dxEditor'
		},
		{	
			dataField: 'video_path',
			editorType: 'VideoUploader',
			label:{text:'视频'},
			cssClass: 'hidden'
		}]
	}
});



crudPages.push({
	route: 'daily-sign',
	url: API('restful?_model=cms-daily-sign'),
	placeholder: '每日签',
	title: '每日签',
	capable: {
		create: true
	},
	search: {
		mobile: 'title',
	},
	columns: [{
		dataField: 'id',
		caption: 'id'
	}, {
		dataField: 'title',
		caption: '名称'
	}, {
		dataField: 'online_at',
		caption: '上线时间'
	}, {
		dataField: 'column_name',
		caption: '类别'
	}, {
		dataField: 'online',
		caption: '上下线',
		cellTemplate:function(con, data) {
			$(con).dxUpdown('article', data)
		}
	},
	{
		caption: '操作',
		buttons:[{
			title:'编辑',
			url:'#/daily-sign/edit/{{id}}',
			del:'cms-daily-sign'
		}]
	}],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		afterDataUpdate: function(formInstance, data) {
			//console.log(formInstance.geiEditor("#editor"));

		},
		beforeSubmit: function(form, id) {
			var formData = form.option('formData');
			var cover = [];
			$.each(formData.covers, function(i, cov) {
				cover.push(cov.id)
			});
			if(cover.length == 0) {
				formData.covers_ids = 0;
			} else {
				formData.cover_ids = cover.join()
			};
			formData.column_id = "1";
			formData.covers = "";
			formData.state = "publish";
			form.option('formData', formData);
			return true;
		},
		items: [{
			itemType: "group",

			items: [{
					dataField: "title",
					label: {
						text: '文章名称'
					},
					validationRules: [{
			            type: "required",
			            message: "请输入名称"
	    			   }]
				},
				{
					dataField: "covers",
					name: "name",
					validationRules:[{
						type:'required'
					}],
					editorType: "ImageUploader",
					label: {
						text: '每日签图片'
					},
					editorOptions: {
						imageWidth: 750,
						imageHeight: 962
					}
				},
				{
					dataField: "online_at",
					label: {
						text: '上线日期'
					},
					editorType: "dxDateBox",
					editorOptions: {
						displayFormat: 'yyyy-MM-dd',
						dateSerializationFormat: 'yyyy-MM-dd HH:mm:ss'

					},
					validationRules: [{
			            type: "required",
			            message: "请输入使用日期"
	    			   }]

				}
			]
		}]
	}
});

crudPages.push({
	route: 'article-column',
	url: API('restful?_model=cms-article-column'),
	title: '文章分类',
	capable: {
		create: true
	},
	columns: [{
		dataField: 'name',
		caption: '栏目名称',
		minWidth: 150
	}, {
		dataField: 'created_at',
		caption: '创建时间'
	}, {
		dataField: 'updated_at',
		caption: '最近修改'
	}, {
		caption: '操作',
		buttons:[{
			title:'编辑',
			url:'#/article-column/edit/{{id}}',
			del:'cms-article-column'
		}]
	}],
	form:{
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		items:[{
			dataField:'name',
			label:{text:'栏目名称'},
			validationRules: [{ type: "required" }],
		}]
	}
});


crudPages.push({
	url: API('restful?_model=sys-admin'),
	route: 'admin-users',
	title: '系统管理员',
	placeholder: '会员名',
	capable: {
		create: true
	},
	buttons: [{
		text: '删除',
		type: 'danger',
		disabled: true,
		onSelectionChanged: function(component, selections, gridComponent) {
			component.option('disabled', selections.length <= 0);
		},
		onClick: function() {
			var store = $.crudStore(API("admin")),
				gridComponent = $("#content .crud-grid").dxDataGrid('instance'),
				selections = gridComponent.getSelectedRowsData(),
				ids = $.map(selections, function(item) {
					return item.id;
				}).join(",");

			DevExpress.ui.dialog.confirm("确定删除吗?", "请确认").done(function(dialogResult) {
				if(dialogResult) {
					store.remove(ids).then(function(resp) {

						DevExpress.ui.notify({
							message: "已删除",
						}, "success", 1000);
						gridComponent.option('dataSource').load();
					});
				}
			});
			return false;
		}
	}],
	columns: [{
		dataField: 'name',
		caption: '名称'
	}, {
		dataField: 'account',
		caption: '账号'
	}, {
		dataField: 'created_at',
		caption: '创建时间'
	},{
		caption:'操作',
		buttons:[{
			title: '编辑',
			url: '#/admin-users/edit/{{id}}'
		}, {
			title: '更改密码',
			url: '#/admin-users/password/edit/{{id}}'
		}, {
			title: '删除',
			onClick: function(data) {
				DevExpress.ui.dialog.confirm("确定删除 " + data.account + " 吗?", "请确认").done(function(dialogResult) {
					if(dialogResult) {
						var ds = App.crudGridInstance().option('dataSource');
						ds.store().remove(data.id).then(function(resp) {
							DevExpress.ui.notify({
								message: "已删除",
							}, "success", 1000);
							ds.reload();
						});
					}
				});
			}
		}]
	}],
	form:{
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		items:[{
			dataField:'name',
			label:{text:'名称'},
			validationRules: [{type: "required"}]
		},{
			dataField:'account',
			label:{text:'帐号'},
			validationRules: [{type: "required"}]
		},{
			scene: ['create'],
			dataField:'password',
			label:{text:'密码'},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{type: "required"}]
		},{
			scene: ['create'],
			dataField:'password_confirmation',
			label:{text:'确认密码'},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{type: "required"}]
		},{
			label:{text:'允许访问ip段'}
		},{
			dataField:'ip_min',
			label:{text:'最小值'}
		},{
			dataField:'ip_max',
			label:{text:'最大值'}
		}]
	}
});

crudPages.push({
	url: API('restful?_model=sys-admin'),
	route: 'admin-users/password',
	title: '更改密码',
	capable: {
		create: false,
		delete: false
	},
	form:{
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		onSaved: function() {
		this.redirect("#/admin-users");
	},
		items:[{
			dataField:'name',
			label:{text:'用户名'},
			validationRules: [{type: "required"}],
			editorOptions: {readOnly: true}
		},{
			dataField:'account',
			label:{text:'帐号'},
			validationRules: [{type: "required"}],
			editorOptions: {readOnly: true}
		},{
			dataField:'password',
			label:{text:'密码'},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{type: "required"}]
		},{
			dataField:'password_confirmation',
			label:{text:'确认密码'},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{type: "required"}]
		}]
	}
});

crudPages.push({
	route: 'area-manage',
	title: '区域',
	columns: [{
		dataField: 'YQXMC',
		caption: '区域名称'
	}, {
		dataField: 'SSMC',
		caption: '上级区域'
	}, {
		dataField: 'id',
		caption: '更新时间'
	}, {
		caption: '操作',
		buttons: [{
			title: '编辑',
			url: ''
		}]
	}]
});

crudPages.push({
	route: 'user-withdraw',
	title: '用户提现',
	capable: {
		create: false
	},
	search: {
		mobile: 'user.mobile',
		name: 'user.uname'
	},
	columns: [{
		dataField: 'user_id',
		caption: '会员id'
	}, {
		dataField: 'card_user_name',
		caption: '持卡人姓名'
	}, {
		dataField: 'subbranch_name',
		caption: '支行'
	}, {
		dataField: 'request_amount',
		caption: '申请提现金额'
	}, {
		dataField: 'request_time',
		caption: '申请时间'
	}, {
		format: function(v) {
			return parseFloat(v).toFixed(2);
		},
		dataField: 'actual_amount',
		caption: '实际打款金额'
	}, {
		dataField: 'status',
		caption: '申请状态'
	}, {
		dataField: 'bank_transaction_no',
		caption: '银行流水号'
	}, {
		dataField: 'remarks',
		caption: '备注'
	}, {
		caption: '操作',
	}]
});

crudPages.push({
	url: API('admin-user'),
	route: 'admin-perm',
	title: '管理员权限',
	placeholder: '会员名 或 邮箱',
	capable: {
		create: false
	},
	search: {
		mobile: ['username', 'email']
	},
	buttons: [{
		text: '分配',
		type: 'normal',
		disabled: true,
		onSelectionChanged: function(component, selections, gridComponent) {
			component.option('disabled', selections.length <= 0);
		},
		//		onClick:function(){
		//			DevExpress.ui.notify({message: "分配成功",}, "success", 1000);
		//		}
	}, {
		text: '删除',
		type: 'danger',
		disabled: true,
		onSelectionChanged: function(component, selections, gridComponent) {
			component.option('disabled', selections.length <= 0);
		},
		onClick: function() {
			var store = $.crudStore(API("admin")),
				gridComponent = $("#content .crud-grid").dxDataGrid('instance'),
				selections = gridComponent.getSelectedRowsData(),
				ids = $.map(selections, function(item) {
					return item.id;
				}).join(",");

			DevExpress.ui.dialog.confirm("确定删除吗?", "请确认").done(function(dialogResult) {
				if(dialogResult) {consoel.log(store.remove(ids));
					store.remove(ids).then(function(resp) {

						DevExpress.ui.notify({
							message: "已删除",
						}, "success", 1000);
						gridComponent.option('dataSource').load();
					});
				}
			});
			return false;
		}
	}],
	columns: [{
		dataField: 'avatar',
		caption: '会员头像',
		allowFiltering: false,
		allowSorting: false,
		cssClass: 'avatarImg',
		cellTemplate: function(container, options) {
			$("<div>").append($("<img>", {
				"src": options.value
			})).appendTo(container);
		}
	}, {
		dataField: 'nickname',
		caption: '会员昵称'
	}, {
		dataField: 'email',
		caption: '邮件地址'
	}, {
		dataField: 'mobile',
		caption: '手机号'
	}, {
		dataField: 'username',
		caption: '会员姓名'
	}, {
		dataField: 'id_card',
		caption: '身份证'
	}, {
		dataField: 'last_login_time',
		caption: '上次登录时间'
	}]
});

crudPages.push({
	url: API('user-role'),
	route: 'wait-audit',
	title: '待审核',
	placeholder: '会员姓名',
	capable: {
		create: false
	},
	search: {
		mobile: 'user.username'
	},
	buttons: [{
			text: '通过',
			type: 'normal',
			disabled: true,
			onSelectionChanged: function(component, selections, gridComponent) {
				component.option('disabled', selections.length <= 0);
			},
			onClick: function() {
				DevExpress.ui.dialog.confirm("确定通过吗?", "请确认").done(function(dialogResult) {
					var gridComponent = $("#content .crud-grid").dxDataGrid('instance');
					var selections = gridComponent.getSelectedRowsData();
					if(selections.length > 0 && dialogResult) {
						var ids = $.map(selections, function(item) {
							return item.id;
						}).join(",");
						$.post(API('user-role-change'), {
							id: ids,
							status: 'approve'
						}).then(function(resp) {

							if(resp.errors) {
								var err = resp.errors.join('<br/>');
								DevExpress.ui.dialog.alert(err, "请确认")
							} else {
								gridComponent.option('dataSource').load();
								DevExpress.ui.notify({
									message: "已更新",
								}, "success", 3000);
							}
						});
					}
				});
				return false;
			}
		}, {
			text: '拒绝',
			type: 'danger',
			disabled: true,
			onSelectionChanged: function(component, selections) {
				component.option('disabled', selections.length <= 0);
			},
			onClick: function() {
				var gridComponent = $("#content .crud-grid").dxDataGrid('instance'),
					selections = gridComponent.getSelectedRowsData();

				if(selections.length > 0) {
					$("<div/>").appendTo($("#popups")).dxPopup({
						title: '填写操作备注',
						height: "auto",
						width: 400,
						visible: true,
						onContentReady: function(e) {
							var $content = e.component.content();

							$content.dxInit();

							$(".confirm", $content).click(function() {
								var v = $("#reject-remark", $content).dxTextArea("option", "value");
								var ids = $.map(selections, function(item) {
									return item.id;
								}).join(",");
								$.post(API('user-role-change'), {
									id: ids,
									status: 'reject',
									remark: v
								}).then(function(resp) {

									gridComponent.option('dataSource').load();
									DevExpress.ui.notify({
										message: "已更新"
									}, "success", 3000);
								});
								e.component.hide();
								return false;
							});

							$(".cancel", $content).click(function() {
								e.component.hide();
								return false;
							});
						},
						contentTemplate: function() {
							var $content = $("<div/>");
							$content.html($("#reject-confirm").html());
							return $content;
						}
					});
				}
			}
		},
		/*{
		text: '导出',
		type: 'normal',
		onClick: function() {
			window.location.href = API('export-withdraw-pending');
		}
	}*/
	],
	columns: [{
		dataField: 'user.username',
		caption: '会员姓名'
	}, {
		dataField: 'code',
		caption: '申请角色',
		cellTemplate: function(c, ci) {
			var a = '',
				code = ci.data.code;
			switch(code) {
				case 'manager':
					a = '项目经理';
					break;
				case 'publish':
					a = '需求录入创客';
					break;
				case 'execute':
					a = '任务执行创客';
					break;
				case 'admin':
					a = '管理员'
					break;
			}
			c.html(a);
		}
	}, {
		dataField: 'format_status',
		caption: '申请状态'
	}, {
		dataField: 'user.mobile',
		caption: '手机号'
	}, {
		dataField: 'user.id_card',
		caption: '身份证号',
	}, {
		dataField: 'created_at',
		caption: '申请时间'
	}],
	store: {
		onLoading: function(loadOptions) {
			loadOptions.filter = ['status', '=', 'pending'];
		}
	}
});

crudPages.push({
	route: 'audited',
	url: API('user-role'),
	title: '已审核',
	placeholder: '会员姓名',
	capable: {
		create: false
	},
	search: {
		mobile: 'user.username',
	},
	columns: [{
		dataField: 'user.username',
		caption: '会员姓名'
	}, {
		dataField: 'code',
		caption: '申请角色',
		cellTemplate: function(c, ci) {
			var a = '',
				code = ci.data.code;
			switch(code) {
				case 'manager':
					a = '项目经理';
					break;
				case 'publish':
					a = '需求录入创客';
					break;
				case 'execute':
					a = '任务执行创客';
					break;
				case 'admin':
					a = '管理员'
					break;
			}
			c.html(a);
		}
	}, {
		dataField: 'format_status',
		caption: '申请状态'
	}, {
		dataField: 'user.mobile',
		caption: '手机号'
	}, {
		dataField: 'user.id_card',
		caption: '身份证号',
	}, {
		dataField: 'created_at',
		caption: '申请时间'
	}, {
		dataField: 'updated_at',
		caption: '处理时间'
	}],
	store: {
		onLoading: function(loadOptions) {
			loadOptions.filter = ['status', '<>', 'pending'];
		}
	}
});

crudPages.push({
	url: API('user-withdraw'),
	route: 'userWithdrawAccept',
	title: '待打款',
	capable: {
		create: false
	},
	search: {
		mobile: 'user.mobile'
	},
	buttons: [{
		text: '导出记录',
		type: 'normal',
		onClick: function() {
			window.location.href = $.config('apiUrl') + 'admin/excel-user-withdraw-export';
		}
	}, {
		text: '导入结果',
		type: 'normal',
		onClick: function() {
			$("<div/>").appendTo($("#popups")).dxPopup({
				title: '更新提现结果',
				height: "auto",
				width: 400,
				visible: true,
				onContentReady: function(e) {
					var dlgComponent = e.component;
					var gridComponent = $("#content .crud-grid").dxDataGrid('instance');
					var $content = e.component.content(),
						uploaded = false;

					$content.dxInit();

					$("#upload-file", $content).dxFileUploader({
						multiple: false,
						accept: "*",
						name: 'file',
						value: [],
						uploadMode: "useButtons",
						uploadUrl: $.config('apiUrl') + 'admin/excel-user-withdraw-import',
						onValueChanged: function(e) {
							if(e.value.length > 0) {
								$(".upload", $content).dxButton("option", "disabled", false);
							} else {
								$(".upload", $content).dxButton("option", "disabled", true);
							}
						},
						onUploaded: function(e) {
							var resp = JSON.parse(e.request.responseText);

							$content.html(Mustache.render($("#import-excel-result").html(), resp));
							$content.dxInit();

							$(".cancel", $content).click(function() {
								dlgComponent.hide();
								return false;
							});

							gridComponent.option('dataSource').load();

							uploaded = true;
						}
					});

					$(".upload", $content).click(function() {
						$(".dx-fileuploader-upload-button", $content).click();
						return false;
					});

					$(".cancel", $content).click(function() {
						e.component.hide();
						return false;
					});
				},
				contentTemplate: function() {
					var $content = $("<div/>");

					$content.html($("#import-excel").html());

					return $content;
				}
			});
		}
	}],
	columns: [{
			dataField: 'user_withdraw_number',
			caption: '提现流水号'
		}, {
			dataField: 'user.uname',
			caption: '会员姓名'
		}, {
			dataField: 'user.mobile',
			caption: '会员手机号'
		}, {
			dataField: 'card_user_name',
			caption: '持卡人姓名',
		}, {
			dataField: 'bank_subbranch_name',
			caption: '开户行',
			width: 300
		}, {
			dataField: 'card_number',
			caption: '卡号'
		}, {
			dataField: 'request_amount',
			caption: '申请提现金额',
			format: function(v) {
				return parseFloat(v).toFixed(2);
			}
		}, {
			dataField: 'request_time',
			caption: '申请时间'
		}
		/*,{
		      	dataField: 'actual_amount',
		        caption: '待打款金额'
		      },{
		      	dataField: 'remarks',
		        caption: '备注'
		      },{
		        caption: '操作',
		        buttons: [{
			        title: '录入打款记录',
			        url: ''
			    }]
		      }*/
	],
	store: {
		onLoading: function(loadOptions) {
			loadOptions.filter = ['status', '=', 1];
		}
	}
});

crudPages.push({
	url: API('user-withdraw'),
	route: 'userWithdrawDone',
	title: '已打款',
	capable: {
		create: false
	},
	search: {
		mobile: 'user.mobile'
	},
	buttons: [{
		text: '导出',
		type: 'normal',
		onClick: function() {
			window.location.href = API('export-withdraw-complete');
		}
	}],
	columns: [{
			dataField: 'user_withdraw_number',
			caption: '提现流水号'
		}, {
			dataField: 'user.uname',
			caption: '会员姓名'
		}, {
			dataField: 'user.mobile',
			caption: '会员手机号'
		}, {
			dataField: 'card_user_name',
			caption: '持卡人姓名',
		}, {
			dataField: 'bank_subbranch_name',
			caption: '开户行',
			width: 200
		}, {
			dataField: 'card_number',
			caption: '卡号'
		}, {
			format: function(v) {
				return parseFloat(v).toFixed(2);
			},
			dataField: 'request_amount',
			caption: '申请提现金额'
		}, {
			dataField: 'request_time',
			caption: '申请时间'
		}
		/*,{
		      	dataField: 'actual_amount',
		        caption: '实际打款金额'
		      },{
		      	dataField: 'bank_transaction_no',
		        caption: '银行流水号'
		      }*/
		, {
			dataField: 'updated_at',
			caption: '打款操作时间'
		}
		/*,{
		      	dataField: 'remarks',
		        caption: '备注'
		      },{
		        caption: '操作',
		        buttons: [{
			        title: '录入打款记录',
			        url: ''
			    }]
		      }*/
	],
	store: {
		onLoading: function(loadOptions) {
			loadOptions.filter = ['status', '=', 2];
		}
	}
});

crudPages.push({
	url: API('user-withdraw'),
	route: 'userWithdrawReject',
	title: '已拒绝',
	capable: {
		create: false
	},
	search: {
		mobile: 'user.mobile'
	},
	buttons: [],
	columns: [{
		dataField: 'user_withdraw_number',
		caption: '提现流水号'
	}, {
		dataField: 'user.uname',
		caption: '会员姓名'
	}, {
		dataField: 'user.mobile',
		caption: '会员手机号'
	}, {
		dataField: 'card_user_name',
		caption: '持卡人姓名',
	}, {
		dataField: 'bank_subbranch_name',
		caption: '开户行'
	}, {
		dataField: 'card_number',
		caption: '卡号'
	}, {
		format: function(v) {
			return parseFloat(v).toFixed(2);
		},
		dataField: 'request_amount',
		caption: '申请提现金额'
	}, {
		dataField: 'request_time',
		caption: '申请时间'
	}, {
		dataField: 'updated_at',
		caption: '拒绝时间'
	}, {
		dataField: 'remarks',
		caption: '备注'
	}],
	store: {
		onLoading: function(loadOptions) {
			loadOptions.filter = ['status', '=', 3];
		}
	}
});

crudPages.push({
	url: API('restful?_model=sys-country'),
	route: 'country',
	title: '国家',
	capable: {
		create: true
	},
	search: {
		mobile: 'chCountry',
		name:'国家名称'
	},

	columns: [{
			dataField: 'id',
			caption: 'id'
		}, {
			dataField: 'chCountry',
			caption: '国家中文名称'
		}, {
			dataField: 'country',
			caption: '国家英文名称'
		}, {
			dataField: 'countryCode',
			caption: '国家代码'
		}, {
			dataField: 'national_flag',
			caption: '国旗',
			cellTemplate:function(container,data){
	        	$("<img>").css({"width":"80px"}).attr("src",data.data['national_flag']).appendTo(container)
			}
		},
		{
			caption:'操作',
			buttons:[{
				title:'编辑',
				url:'#/country/edit/{{id}}',
				del:'sys-country'
			}]
		}
	],
	form:{
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		items:[{
			dataField:'chCountry',
			label:{text:'中文名称'}
		}, {
			dataField:'country',
			label:{text:'英文名称'}
		}, {
			dataField:'countryCode',
			label:{text:'国家代码'}
		}, {
			dataField:'national_flag',
			label:{text:'国旗'},
			editorType:'ImageUploader',
			editorOptions: {
				single: true
			}
		}]}
});
crudPages.push({
	url: API('rights-change'),
	route: 'rightsChange',
	title: '权益变更',
	capable: {
		create: false
	},
	search: {
		mobile: 'user.mobile',
	},
	buttons: [{
		text: '新增变更记录',
		type: 'normal',
		onRoute: function(component, selections) {
			this.redirect('#/rightsChanges');
		}
	}],
	columns: [{
		dataField: 'number',
		caption: '记录编号'
	}, {
		dataField: 'user.mobile',
		caption: '会员手机'
	}, {
		dataField: 'user.username',
		caption: '会员姓名'
	}, {
		dataField: 'change_type',
		caption: '变更类型',
		cellTemplate: function(c, ci) {
			ci.data.change_type == 1 ? c.html("<span style='color:green'>增加</span>") : c.html("<span style='color:red'>减少</span>")
		}
	}, {
		dataField: 'change_cate',
		caption: '权益类型',
		cellTemplate: function(c, ci) {
			ci.data.change_cate == 'sea' ? c.html("出海") : c.html("静泊")
		}
	}, {
		dataField: 'time',
		caption: '变更时长'
	}, {
		dataField: 'remark',
		caption: '备注'
	}, {
		dataField: 'file',
		caption: '附件'
	}, {
		dataField: 'created_at',
		caption: '创建时间'
	}],
});

crudPages.push({
	url: API('restful?_model=expert-user'),
	route: 'expert-user',
	title: '专家',
	capable: {
		create: true
	},
	search: {
		mobile: false
	},
	columns: [ {
			dataField: 'id',
			caption: 'id'
		}, {
			dataField: 'name',
			caption: '会员名'
		}, {
			dataField: 'account',
			caption: '帐户名称'
		},
		{
			caption: '操作',
			cellTemplate:function(con,dat){
				$("<a href='#' style='padding-right: 10px;'>编辑</a>").click(function () {
					App.getEventContext().redirect('#/expert-user/edit/' + dat.data.id);
					return false;
				}).appendTo($(con));

				$(con).dxDelete('expert-user',dat)
			}
		}
	],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		afterDataUpdate: function(formInstance, data) {
			//console.log(formInstance.geiEditor("#editor"));

		},
		items: [{
			itemType: "group",

			items: [{
					dataField: "account",
					label: {
						text: '专家姓名'
					},
					validationRules: [{type: "required"}]
				},
				{
					dataField: "avatar",
					editorType: "ImageUploader",
					label: {
						text: '头像'
					},
					editorOptions: {
						single: true
					}

				},
				{
					dataField: "intro",
					label: {
						text: '个人简介'
					},
					editorType: "dxTextArea",
					editorOptions: {
						height: 90,
						autoResizeEnabled: false,

					}
				}
			]
		}]
	}

});

crudPages.push({
	url: API('restful?_model=wine-product-qrcode'),
	route: 'qrcode',
	title: '二维码发放',
	capable: {
		create: true
	},
	buttons: [],
	columns: [{
		dataField: 'created_at',
		caption: '发放时间'
	}, {
		dataField: 'amount',
		caption: '发放数量'
	}, {
		dataField: 'chateauCode',
		caption: '酒庄码'
	}, {
		dataField: 'countryCode',
		caption: '国家码'
	}, {
		dataField: 'subdivisionCode',
		caption: '地区码'
	}, {
		dataField: 'regionCode',
		caption: '产区码'
	}, {
		dataField: 'productCode',
		caption: '产品码'
	}, {
		dataField: 'vintage',
		caption: '年份'
	}, {
		caption: '操作',
		buttons: [{
			title: '导出',
			onClick: function(data, instance) {
				location.href = data.download_url;				
			}
		}, {
			title: '查看',
			url: '#/qrcode-record/{{id}}'
		}]
	}],
	form: {
		items: [{
			dataField: 'chateau_id',
			label: { text: '酒庄' },
			editorType: 'dxSelectBox',
			editorOptions: {
				dataSource: $.crudStore(API('restful?_model=wine-chateau')),
                showClearButton: true,
                placeholder: "酒庄",
                searchEnabled: true,
                valueExpr: 'id',
                noDataText: '没有请求到酒庄数据',
                itemTemplate: function(data, index, $el) {
                  if (data) {
                    $("<span>" + data.chname + " (" + data.name + ")</span>").appendTo($el);
                  }
                },
                displayExpr: function(data) {
                  return data ? data.chname + " (" + data.name + ")" : "";
                },
                onValueChanged: function(e) {
                	setTimeout(function () {
                		var formInstance = App.getFormInstance();

                		if (formInstance) {
                			var inst = formInstance.getEditor('product_id');
                			inst.option('disabled', ! e.value);

                			if (e.value) {
                				inst.option('dataSource').filter('chateau_id', '=', e.value);
                				inst.option('dataSource').reload();
                			}
                		}
                	}, 0);
                }
			}
		}, {
			dataField: 'product_id',
			label: { text: '产品' },
			editorType: 'dxSelectBox',
			editorOptions: {
                dataSource: new DevExpress.data.DataSource({
                	store: $.crudStore(API("restful?_model=wine-product"))
                }),
                searchEnabled: true,
                valueExpr: 'id',
                noDataText: '没有请求到产品数据',
                disabled: true,
                itemTemplate: function(data, index, $el) {
                  if (data) {
                    $("<span>" + data.chname + " (" + data.name + ")</span>").appendTo($el);
                  }
                },
                displayExpr: function(data) {
                  return data ? data.chname + " (" + data.name + ")" : "";
                }
			}
		}, {
			dataField: 'vintage',
			label: { text: '年份' },
			editorType: 'YearSelect',
			editorOptions: {}
		}, {
			dataField: 'amount',
			label: { text: '数量' },
			editorType: 'dxNumberBox',
			editorOptions: {}
		}]
	}
});

crudPages.push({
	url: API('restful?_model=sys-produce'),
	route: 'producer',
	title: '生产商',
	capable: {
		create: true
	},
	buttons: [],
	columns: [{
		dataField: 'created_at',
		caption: '创建时间'
	}, {
		dataField: 'name',
		caption: '名称'
	}, {
		dataField: 'chname',
		caption: '中文名称'
	}, {
		dataField: 'produceCode',
		caption: '生产商码'
	}, {
		caption: '操作',
		buttons: [{
			title: '编辑',
			url: '#/producer/edit/{{id}}'
		}]
	}],
	form: {
		items: [{
			dataField: 'produceCode',
			label: { text: '生产商码' },
			editorType: 'dxTextBox',
			editorOptions: {},
			validationRules: [{ type: "required" }]
		}, {
			dataField: 'name',
			label: { text: '名称' },
			editorType: 'dxTextBox',
			editorOptions: {},
			validationRules: [{ type: "required" }]
		}, {
			dataField: 'chname',
			label: { text: '中文名称' },
			editorType: 'dxTextBox',
			editorOptions: {},
			validationRules: [{ type: "required" }]
		}, {
			dataField: 'logo',
			label: { text: 'LOGO' },
			editorType: 'ImageUploader',
			editorOptions: {
				single: true
			}
		}]
	}
});

crudPages.push({
	url: API('restful?_model=wine-qrcode-record'),
	route: 'qrcode-record/:qrcode_id',
	title: '二维码记录',
	capable: {
		create: false
	},
	buttons: [],
	columns: [{
		dataField: 'created_at',
		caption: '创建时间'
	}, {
		dataField: 'code',
		caption: '编码'
	}, {
		dataField: 'sortno',
		caption: '序码'
	}, {
		dataField: 'state',
		caption: '状态',
		cellTemplate: function(c, ci) {
			c.html('未扫码');
		}
	}, {
		caption: '操作',
		buttons: [{
			title: '查看',
			onClick: function(data, instance) {
				$("<div/>").appendTo($("#popups")).dxPopup({
					title: '查看二维码',
					visible: true,
					width: 360,
					height: 360,
					onContentReady: function(e) {
						var $content = e.component.content();

						new QRCode($(".qrcode", $content)[0], $.config('qrCodeUrl') + data.code);
					},
					contentTemplate: function() {
						var $content = $("<div style='text-align: center;'><div class='qrcode' style='display: inline-block;'></div></div>");
						return $content;
					}
				});
			}
		}]
	}]
});

crudPages.push({
	url: API('restful?_model=focus-picture'),
	route: 'banner',
	title: '焦点图',
	capable: {
		create: true
	},
	buttons: [],
	columns: [{
		dataField: 'pic',
		caption: '图片',
		cellTemplate: function(c, ci) {
			$("<img src='" + ci.data.pic + "?imageView2/0/h/60'/>").appendTo(c);
		}
	}, {
		dataField: 'created_at',
		caption: '创建时间'
	}, {
		dataField: 'title',
		caption: '标题'
	}, {
		dataField: 'type',
		caption: '类型',
		cellTemplate: function(c, ci) {
			c.html(ci.data.type === 'article' ? '文章' : '葡萄酒');
		}
	}, {
		dataField: 'weight',
		caption: '权重',
		cellTemplate:function(con, da){
			$(con).dxWeight("focus",da);
		}
	}, {
		caption: '操作',
		cellTemplate:function(con,dat){
			$("<a href='#' style='padding-right: 10px;'>编辑</a>").click(function () {
				App.getEventContext().redirect('#/banner/edit/' + dat.data.id);
				return false;
			}).appendTo($(con));

			$(con).dxDelete('focus-picture',dat)
		}
	}],
	form: {
		beforeDataUpdate: function(formInstance, e) {
			e.data.obj_id = parseInt(e.data.obj_id);
		},
		items: [{
			dataField: 'title',
			label: { text: '标题' },
			editorType: 'dxTextBox',
			editorOptions: {},
			validationRules: [{ type: "required" }]
		}, {
			dataField: 'pic',
			label: { text: '封面图片' },
			editorType: 'ImageUploader',
			editorOptions: {
				single: true,
				imageWidth: 750,
				imageHeight: 422
			},
			validationRules: [{ type: "required" }]
		}, {
			dataField: 'type',
			label: { text: '类型' },
			validationRules: [{ type: "required" }],
			editorType: 'dxRadioGroup',
          	editorOptions: {
	            layout: "horizontal",
	            valueExpr: 'value',
	            dataSource: [{
	              text: '文章',
	              value: 'article'
	            }, {
	              text: '葡萄酒',
	              value: 'product'
	            }],
	            onValueChanged: function(e) {
	            	var formInstance = App.getFormInstance();

	            	// formInstance.updateData({obj_id: 0});

	            	if (e.value === 'article') {
	    				formInstance.getEditor('obj_id').option({
	    					dataSource: $.crudStore(API('restful?_model=cms-article'))
	    				});
    				} else {
	    				formInstance.getEditor('obj_id').option({
	    					dataSource: $.crudStore(API('restful?_model=product'))
	    				});
    				}
	            }
          	}
		}, {
			dataField: 'obj_id',
			label: { text: '文章/葡萄酒' },
			validationRules: [{ type: "required" }],
			editorType: 'dxSelectBox',
			editorOptions: {
				dataSource: $.crudStore(API('restful?_model=cms-article')),
				showClearButton: true,
				searchEnabled: true,
				valueExpr: 'id',
				noDataText: '没有请求到数据',
				itemTemplate: function(data, index, $el) {
				  if (data && data.chname && data.name) {
				    $("<span>" + data.chname + " (" + data.name + ")</span>").appendTo($el);
				  } else if (data && data.title) {
				  	$("<span>" + data.title + "</span>").appendTo($el);
				  }
				},
				displayExpr: function(data) {
					if (data && data.chname && data.name) {
					  return data.chname + " (" + data.name + ")";
					} else if (data && data.title) {
						return data.title;
					} else {
						return "";
					}
				}
			}
		}]
	}
});

$(function() {
	if(!localStorage.accessToken) {
		window.location.href = 'login.html';
		return;
	} else {
		$.ajax({
			headers: {
				Authorization: "bearer " + localStorage.accessToken
			},
			url: API('auth/me'),
			type: 'get',
			success: function(resp) {
				$(".app").show();

				var data = resp.data, type = data.userType;
				// if (data.userType === 'super' && data.account === 'admin') {
				// 	type = 'super';
				// }

				$(".admin-name").text(data.username);
				$(".auth-" + type).show();

				App.setUser(data);
			},
			error: function(resp) {
				window.location.href = 'login.html';

			}
		});
	}

	DevExpress.viz.currentTheme("generic.light");

	$("body").dxInit();

	var app = $.sammy('#content', function() {
		var app = this;

		for(var i = 0; i < routes.length; i++) {
			(function(route) {
				var m = route.match(/[^\/]*/);
				app.get('#/' + route, function() {

					var eventContext = this;

					$.get('template/' + m[0] + '.html', function(resp) {
						$('#content').html(resp).dxInit();
						$("#content").trigger("route.loaded", [eventContext])
					});
				});
			})(routes[i]);
		}

		$.each(crudPages, function(i, page) {
			$.crud($.extend({
				app: app
			}, page));
		})

	});

	app.bind('changed', {}, function() {
		App.setEventContext(this);
	});
	app.run('#/product');

});
